<template>
  <div class="fixed-sign-contract">
    <van-nav-bar :border="false" placeholder fixed>
      <template #left>
        <svg-icon name="arrows" @click="topReturnClick" />
      </template>
      <template #title>
        <span class="contract-title">待签文件</span>
      </template>
    </van-nav-bar>
    <div class="fixed-name">
      <div class="contract-name">{{ contractName }}</div>
    </div>
    <!-- 合同图片 -->
    <div class="contract-img">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        @load="changeContractImageList"
        :immediate-check="false"
      >
        <template v-for="(item, index) in contractImageList" :key="item">
          <div class="contract-content">
            <img :src="`data:image/png;base64,${item}`" alt="" />
            <template v-for="signItem in signingCoordList" :key="item">
              <!-- 印章 -->
              <template v-if="signItem.controlType === 'signseal'">
                <div
                  class="sign-write"
                  :style="`width:${signItem.signWidth}px;height:${signItem.signHeight}px;top:${signItem.ycoord}px;left:${signItem.xcoord}px;`"
                  v-if="signItem.pageNum - 1 === index"
                  @click="writeSignClick('newAddSign')"
                >
                  <img v-show="fixedSigningImg" :src="fixedSigningImg" alt="" />
                </div>
              </template>
              <!-- 时间控件 -->
              <template v-if="signItem.controlType === 'signdate'">
                <div
                  class="sign-write"
                  :style="`width:${signItem.signWidth}px;height:${signItem.signHeight}px;top:${signItem.ycoord}px;left:${signItem.xcoord}px;`"
                  v-if="signItem.pageNum - 1 === index"
                >
                  {{ fiexdSigningDate }}
                </div>
              </template>
            </template>
          </div>
        </template>
      </van-list>
    </div>
    <div class="sign-bottom">
      <div class="sign" @click="writeSignClick('newAddSign')">
        <svg-icon name="write" className="write-icon" />
        <span class="write-text">手写签名</span>
      </div>
      <div class="sign">
        <svg-icon name="seal" className="write-icon" />
        <span class="write-text">盖章</span>
      </div>
      <van-button class="bottom-btn" type="primary" @click="signTypeSelect"
        >提交</van-button
      >
    </div>
  </div>
  <write-sign-img ref="writeSignImgRef" @signBase64Img="signBase64Img" />
  <!-- 刷脸签署 -->
  <face-swiping ref="faceSwipingRef" />
  <!-- 短信签署 -->
  <code-sign ref="codeSignRef" @codeSignClick="CodesignClick" />
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from '@/store'
import { Dialog, Toast } from 'vant'

import WriteSignImg from '@/components/write-sign-img'
import faceSwiping from '@/components/face-swiping'
import codeSign from '@/components/code-sign'
import {
  getContractAllInfo,
  getContractBase64Img,
  postFixedSignData,
  getSigningPattern,
  getSystemDate
} from '@/api/contract'
import { getItem, setItem } from '@/utils/storage'
import { formattingDate } from '@/hooks/filter'
export default defineComponent({
  components: { WriteSignImg, faceSwiping, codeSign },
  setup() {
    const store = useStore()
    const route = useRoute()
    const router = useRouter()
    const contractId = ref('')
    const contractName = ref('')
    const contractImageList = ref<any>([]) // 合同图片信息
    const loading = ref(false)
    const finished = ref(false)
    const imageData = reactive({
      total: 0,
      PageNumber: 1,
      filePath: ''
    })
    contractId.value = route.query.contractId as string
    // 获取合同信息
    const getContractList = async () => {
      const res = await getContractAllInfo({ contractId: contractId.value })
      if (res.code !== '0') return
      const list = res.data
      contractName.value = list.contractBaseInfo.title // 代签文件
      const fileList = list.signingFileInfoList.map((item: any) => {
        return {
          fileId: item.fileId,
          fileName: item.fileName,
          filePath: item.filePath,
          filePages: item.filePages
        }
      })
      imageData.total = fileList[0].filePages
      imageData.filePath = fileList[0].filePath
      await changeContractImageList()
      await initSigningLocation(list)
    }
    // 请求图片信息
    const changeContractImageList = async () => {
      for (let i = imageData.PageNumber; i <= imageData.PageNumber; i++) {
        const res = await getContractBase64Img({
          filePath: imageData.filePath,
          pageNum: i
        })
        if (res.code !== '0') return
        contractImageList.value.push(res.data)
      }
      imageData.PageNumber++
      loading.value = false
      if (contractImageList.value.length >= imageData.total) {
        finished.value = true
      }
    }

    // 获取系统时间
    const fiexdSigningDate = ref('') // 控件时间
    const changeSystemDate = async () => {
      const res = await getSystemDate()
      if (res.code !== '0') return
      const { yyyy, MM, dd } = formattingDate(res.data.systemDate)
      fiexdSigningDate.value = `${yyyy}年${MM}月${dd}日`
    }

    // 加载印章位置
    const contractH = route.query.contractH as any
    const contractW = route.query.contractW as any
    interface ISigningData {
      controlType: string
      id: string
      pageNum: number
      xcoord: number
      ycoord: number
      xpercent: number
      ypercent: number
      signWidth: number
      signHeight: number
    }
    const signingCoordList = ref<ISigningData[]>([])
    signingCoordList.value =
      getItem(`${contractId.value}_${route.query.uuid}_cooreds`) ?? []
    const fixedSigningImg = ref('') // 印章图片
    fixedSigningImg.value =
      getItem(`${contractId.value}_${route.query.uuid}_signImg`) ?? ''
    const initSigningLocation = (list: any) => {
      const currentSigning = list.signingFileCoordInfoList.filter(
        (item: any) => {
          if (list.contractBaseInfo.curSignerType === 1) {
            // 企业签署
            if (
              item.signerType === 1 &&
              list.contractBaseInfo.curOrgIdnumber === item.orgIdnumber
            ) {
              if (list.contractBaseInfo.curUserIdnumber === item.userIdnumber) {
                return item
              }
            }
          } else if (list.contractBaseInfo.curSignerType === 2) {
            // 个人签署
            if (
              item.signerType === 2 &&
              list.contractBaseInfo.curUserIdnumber === item.userIdnumber
            ) {
              return item
            }
          }
        }
      )
      // 控件
      signingCoordList.value = currentSigning.map((item: any) => {
        let width = 0
        let height = 0
        if (item.controlType === 'signseal') {
          // 签署控件
          if (item.signerType === 1) {
            // 公司名章
            width = contractW * 0.190476
            height = width
          } else if (item.signerType === 2) {
            // 个人名章
            width = contractW * 0.095
            height = contractH * 0.048
          }
        } else if (item.controlType === 'signdate') {
          // 签署时间控件
          height = contractH * 0.02
          width = contractW * 0.25
        }

        return {
          controlType: item.controlType, // 控件类型
          id: item.id,
          pageNum: item.filePageNumber,
          xcoord: ((item.xpercent * contractW) / 100).toFixed(2),
          ycoord: (contractH - (item.ypercent * contractH) / 100).toFixed(2),
          xpercent: item.xpercent,
          ypercent: item.ypercent,
          signWidth: width,
          signHeight: height
        }
      })
    }

    // 手写签名
    const writeSignImgRef = ref<InstanceType<typeof WriteSignImg>>()
    const writeSignClick = (signType: string) => {
      writeSignImgRef.value!.showWriteSignClick(signType)
    }

    const signBase64Img = (base64: string) => {
      if (fixedSigningImg.value && fixedSigningImg.value !== base64) {
        Dialog.confirm({
          title: '所选印章与当前印章不同',
          message: '是否使用当前所选印章'
        })
          .then(() => {
            fixedSigningImg.value = base64
          })
          .catch(() => {})
      } else {
        fixedSigningImg.value = base64
      }
    }

    // 立即签署
    const authcWay = ref(2) // 2为短信，3为刷脸
    const changeSignPattern = async () => {
      const res = await getSigningPattern()
      if (res.code !== '0') return
      authcWay.value =
        +res.data.org.orgBasicInfoConfigEntity.userSignModeConfigValue
    }
    const faceSwipingRef = ref<InstanceType<typeof faceSwiping>>()
    const codeSignRef = ref<InstanceType<typeof codeSign>>()
    const signTypeSelect = () => {
      if (!fixedSigningImg.value || !fixedSigningImg.value.length) {
        return Toast.fail('请先放置印章')
      }
      if (authcWay.value === 2) {
        codeSignRef.value!.showCodeSignPopup()
      } else if (authcWay.value === 3) {
        // 存储当前控件
        const coordsKey = `${contractId.value}_${route.query.uuid}_cooreds`
        const signImg = `${contractId.value}_${route.query.uuid}_signImg`
        setItem(coordsKey, signingCoordList.value)
        setItem(signImg, fixedSigningImg.value)
        faceSwipingRef.value!.showFaceSwipingPopup()
      }
    }
    // 短信签
    const CodesignClick = async (data: {
      vcode: string
      randomCode: number
    }) => {
      const coords = signingCoordList.value.map((item: ISigningData) => {
        return {
          pageNum: item.pageNum,
          xcoord: +item.xcoord,
          ycoord: +item.ycoord,
          xpercent: item.xpercent,
          ypercent: item.ypercent
        }
      })
      const uuid = new Date().getTime()
      const params = {
        contractId: contractId.value,
        bizNo: uuid,
        sealImg: fixedSigningImg.value.replace(/^data:image\/\w+;base64,/, ''),
        authcWay: authcWay.value,
        coords: coords, // 章
        vcode: data.vcode,
        randomCode: data.randomCode
      }
      const res = await postFixedSignData(params)
      if (res.code !== '0') return
      router.push({
        path: '/contract-sign-success',
        query: {
          contractId: contractId.value
        }
      })
    }
    // 刷脸签
    const faceSwipingSignClick = async () => {
      const coords = signingCoordList.value.map((item: ISigningData) => {
        return {
          pageNum: item.pageNum,
          xcoord: +item.xcoord,
          ycoord: +item.ycoord,
          xpercent: item.xpercent,
          ypercent: item.ypercent
        }
      })
      const uuid = new Date().getTime()
      const orderNo = getItem('bizNo')
      const params = {
        contractId: contractId.value,
        bizNo: uuid,
        sealImg: fixedSigningImg.value.replace(/^data:image\/\w+;base64,/, ''),
        authcWay: authcWay.value,
        coords: coords, // 章
        faceDto: {
          realName: store.state.login.userInfo.userName,
          certificateNumber: store.state.login.userInfo.idNumber,
          isPhone: true,
          orderNo: orderNo // 订单号
        }
      }
      const res = await postFixedSignData(params)
      if (res.code !== '0') return
      router.push({
        path: '/contract-sign-success',
        query: {
          contractId: contractId.value
        }
      })
    }

    // 返回
    const topReturnClick = () => {
      router.push({
        path: '/check-contract',
        query: {
          contractId: contractId.value
        }
      })
    }
    // 初始化数据
    const init = async () => {
      // 刷脸回调
      if (route.query.thirdparty) {
        await faceSwipingSignClick()
      }
      await getContractList()
      await changeSignPattern()
      await changeSystemDate()
    }
    init()

    return {
      contractName,
      writeSignImgRef,
      faceSwipingRef,
      codeSignRef,
      loading,
      finished,
      contractImageList,
      fixedSigningImg,
      fiexdSigningDate,
      signingCoordList,
      signBase64Img,
      topReturnClick,
      writeSignClick,
      changeContractImageList,
      signTypeSelect,
      CodesignClick
    }
  }
})
</script>

<style scoped lang="less">
.fixed-sign-contract {
  position: relative;
  width: 100%;
  height: 100%;
  .contract-title {
    font-size: 17px;
    color: #101010;
    font-weight: 700;
  }
  .fixed-name {
    height: 41px;
    width: 100%;
    .contract-name {
      position: fixed;
      top: 46px;
      left: 0;
      height: 40px;
      width: 100%;
      background-color: #fff;
      border-bottom: 1px solid #e0e0e0;
      font-size: 13px;
      line-height: 41px;
      padding-left: 20px;
      color: #101010;
    }
  }
  .contract-img {
    height: calc(100% - 147px);
    overflow: hidden;
    overflow-y: auto;
    .contract-content {
      position: relative;
      margin-bottom: 10px;
      img {
        display: block;
        width: 100%;
      }
      // 印章
      .sign-write {
        position: absolute;
        border: 1px dashed rgb(0, 175, 161);
        background: rgb(220, 230, 241);
        font-size: 12px;
        img {
          display: block;
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .sign-bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    height: 59px;
    width: 100%;
    background-color: #fff;
    border-top: 1px solid #e0e0e0;
    display: flex;
    justify-content: space-around;
    align-items: center;
    .sign {
      display: flex;
      align-items: center;
      .write-icon {
        font-size: 19px;
        margin-right: 7px;
      }
      .write-text {
        font-size: 12px;
      }
    }
    .bottom-btn {
      width: 140px;
      height: 40px;
      font-size: 16px;
    }
  }
}
</style>
